﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatternPractice.Structural.Composite
{
    public abstract class Component
    {
        public string Name { get; private set; }//基于显示考虑，此属性和对它的所有操作与组合模式无关
        public int Level { get; private set; } = 0;//此属性和对它的所有操作与组合模式无关，实际使用时，如有需要，可以用来表示节点在树中的层级

        public List<Component> Children { get; private set; } = new List<Component>();

        public Component(string name)
        {
            Name = name;
        }

        public abstract void Operation();

        public virtual void Add(Component component)
        {
            Children.Add(component);
            AdjustLevel();
        }

        public virtual void Remove(Component component)
        {
            Children.Remove(component);
        }

        /// <summary>
        /// 与组合模式无关
        /// </summary>
        private void AdjustLevel()
        {
            foreach (var child in Children)
            {
                child.Level = Level + 1;
                if (child.Children.Count() > 0)
                {
                    child.AdjustLevel();
                }
            }
        }

        /// <summary>
        /// 用于美化显示，与组合模式无关
        /// </summary>
        protected void ShowBlank()
        {
            for (int i = 0; i < Level; i++)
            {
                Console.Write("  ");
            }
        }
    }
}